{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b06298de-86d0-4cf0-a494-bcef2b6c837e",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://mirrors.aliyun.com/pypi/simple/\n",
      "Collecting pystac\n",
      "  Downloading https://mirrors.aliyun.com/pypi/packages/08/e4/3e66e30c9c76cb0ac4328af498dd3e900fd7a63bc31edc8323e21c2abe61/pystac-1.8.1-py3-none-any.whl (169 kB)\n",
      "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m169.5/169.5 kB\u001b[0m \u001b[31m1.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0ma \u001b[36m0:00:01\u001b[0m\n",
      "\u001b[?25hRequirement already satisfied: python-dateutil>=2.7.0 in /storage/DevEnv/python/py39/lib/python3.9/site-packages (from pystac) (2.8.2)\n",
      "Requirement already satisfied: six>=1.5 in /storage/DevEnv/python/py39/lib/python3.9/site-packages (from python-dateutil>=2.7.0->pystac) (1.16.0)\n",
      "Installing collected packages: pystac\n",
      "Successfully installed pystac-1.8.1\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip install pystac"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ef0ef7a4-cae1-4a89-9c19-2c2aa8d7ef3b",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Looking in indexes: https://mirrors.aliyun.com/pypi/simple/\n",
      "Collecting pathlib\n",
      "  Downloading https://mirrors.aliyun.com/pypi/packages/78/f9/690a8600b93c332de3ab4a344a4ac34f00c8f104917061f779db6a918ed6/pathlib-1.0.1-py3-none-any.whl (14 kB)\n",
      "Installing collected packages: pathlib\n",
      "Successfully installed pathlib-1.0.1\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "pip install pathlib "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "d7b0bc76-b369-4c07-8f1e-3def3984dc79",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<Catalog id=Paranapanema>\n"
     ]
    }
   ],
   "source": [
    "from pathlib import Path\n",
    "import pystac\n",
    "\n",
    "catalog = pystac.Catalog(\n",
    "    id='Paranapanema',\n",
    "    description='Water masks from Paranapanema basin',\n",
    "    stac_extensions=['https://stac-extensions.github.io/projection/v1.0.0/schema.json']\n",
    ")\n",
    "print(catalog)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "7654d4a4-5d04-4936-8643-3a2e6ef66e8e",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from shapely.geometry import Polygon, mapping\n",
    "import rasterio as rio\n",
    "\n",
    "def get_bbox_and_footprint(dataset):\n",
    "\n",
    "    # create the bounding box it will depend if it comes from rasterio or rioxarray\n",
    "    bounds = dataset.bounds\n",
    "\n",
    "    if isinstance(bounds, rio.coords.BoundingBox):\n",
    "        bbox = [bounds.left, bounds.bottom, bounds.right, bounds.top]\n",
    "    else:\n",
    "        bbox = [float(f) for f in bounds()]\n",
    "\n",
    "    # create the footprint\n",
    "    footprint = Polygon([\n",
    "        [bbox[0], bbox[1]],\n",
    "        [bbox[0], bbox[3]],\n",
    "        [bbox[2], bbox[3]],\n",
    "        [bbox[2], bbox[1]]\n",
    "    ])\n",
    "\n",
    "    return bbox, mapping(footprint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2f41ec1d-7ad9-4edc-934d-f0cd8f4a2275",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "* <Catalog id=Paranapanema>\n"
     ]
    }
   ],
   "source": [
    "from pathlib import Path\n",
    "import pandas as pd\n",
    "from rasterio.warp import transform_bounds, transform_geom\n",
    "\n",
    "# get a list of files\n",
    "folder = Path('./paranapanema/')\n",
    "masks = list(folder.rglob('*watermask.tif'))\n",
    "\n",
    "for mask in masks:\n",
    "\n",
    "    # open the mask with rasterio\n",
    "    ds = rio.open(mask)\n",
    "\n",
    "    bbox, footprint = get_bbox_and_footprint(ds)\n",
    "\n",
    "    # Project to WGS84 to obtain in geometric coordinates\n",
    "    geo_bounds = transform_bounds(ds.crs, 'EPSG:4326', *bbox)\n",
    "    geo_footprint = transform_geom(ds.crs, 'EPSG:4326', footprint)\n",
    "\n",
    "    # properties\n",
    "    idx = mask.stem[:38]\n",
    "    date = pd.to_datetime(mask.stem[11:26])\n",
    "    tile = mask.parts[1]\n",
    "\n",
    "    item = pystac.Item(\n",
    "        id=idx,\n",
    "        geometry=geo_footprint,\n",
    "        bbox=geo_bounds,\n",
    "        datetime=date,\n",
    "        stac_extensions=['https://stac-extensions.github.io/projection/v1.0.0/schema.json'],\n",
    "        properties=dict(\n",
    "            tile=tile\n",
    "        )\n",
    "    )\n",
    "\n",
    "    catalog.add_item(item)\n",
    "\n",
    "print(len(list(catalog.get_items())))\n",
    "catalog.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "7598d113-6fdb-49dc-9d54-fbb69f0da125",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<Catalog id=Paranapanema>\n",
      "0\n",
      "* <Catalog id=Paranapanema>\n"
     ]
    }
   ],
   "source": [
    "from pathlib import Path\n",
    "import pystac\n",
    "\n",
    "catalog = pystac.Catalog(\n",
    "    id='Paranapanema',\n",
    "    description='Water masks from Paranapanema basin',\n",
    "    stac_extensions=['https://stac-extensions.github.io/projection/v1.0.0/schema.json']\n",
    ")\n",
    "print(catalog)\n",
    "\n",
    "from shapely.geometry import Polygon, mapping\n",
    "import rasterio as rio\n",
    "\n",
    "def get_bbox_and_footprint(dataset):\n",
    "\n",
    "    # create the bounding box it will depend if it comes from rasterio or rioxarray\n",
    "    bounds = dataset.bounds\n",
    "\n",
    "    if isinstance(bounds, rio.coords.BoundingBox):\n",
    "        bbox = [bounds.left, bounds.bottom, bounds.right, bounds.top]\n",
    "    else:\n",
    "        bbox = [float(f) for f in bounds()]\n",
    "\n",
    "    # create the footprint\n",
    "    footprint = Polygon([\n",
    "        [bbox[0], bbox[1]],\n",
    "        [bbox[0], bbox[3]],\n",
    "        [bbox[2], bbox[3]],\n",
    "        [bbox[2], bbox[1]]\n",
    "    ])\n",
    "\n",
    "    return bbox, mapping(footprint)\n",
    "\n",
    "import pandas as pd\n",
    "from rasterio.warp import transform_bounds, transform_geom\n",
    "\n",
    "# get a list of files\n",
    "folder = Path('./paranapanema/')\n",
    "masks = list(folder.rglob('*watermask.tif'))\n",
    "\n",
    "for mask in masks:\n",
    "\n",
    "    # open the mask with rasterio\n",
    "    ds = rio.open(mask)\n",
    "\n",
    "    bbox, footprint = get_bbox_and_footprint(ds)\n",
    "\n",
    "    # Project to WGS84 to obtain in geometric coordinates\n",
    "    geo_bounds = transform_bounds(ds.crs, 'EPSG:4326', *bbox)\n",
    "    geo_footprint = transform_geom(ds.crs, 'EPSG:4326', footprint)\n",
    "\n",
    "    # properties\n",
    "    idx = mask.stem[:38]\n",
    "    date = pd.to_datetime(mask.stem[11:26])\n",
    "    tile = mask.parts[1]\n",
    "\n",
    "    item = pystac.Item(\n",
    "        id=idx,\n",
    "        geometry=geo_footprint,\n",
    "        bbox=geo_bounds,\n",
    "        datetime=date,\n",
    "        stac_extensions=['https://stac-extensions.github.io/projection/v1.0.0/schema.json'],\n",
    "        properties=dict(\n",
    "            tile=tile\n",
    "        )\n",
    "    )\n",
    "\n",
    "    catalog.add_item(item)\n",
    "\n",
    "print(len(list(catalog.get_items())))\n",
    "catalog.describe()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b148131-de14-4322-b5d8-a46613fceecc",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
